package org.common.util;

import java.util.Arrays;

import org.springframework.util.StringUtils;

/**
 * java 数字前缀()
 * @author lenovo
 *
 */
public class NumUtils {

	
	/**
	 * 将无符号整型转化为byte类型(有符号)
	 * @param n
	 * @return
	 */
	public static byte fromUnsignedInt(int n){
		return (byte)n;
	}
	/**
	 * 将有符号的byte转为无符号的整型
	 * @param n
	 * @return
	 */
	public static int toUnsignedInt(byte n){
		return Byte.toUnsignedInt(n);
	}
	/**
	 * 
	 * @param n
	 * @return
	 */
	public static String toHexString(byte n){
		return Integer.toHexString(Byte.toUnsignedInt(n));
	}
	public static byte[] readBytes(byte[] datas,int index,int len) throws Exception{
		return Arrays.copyOfRange(datas, index, index+len);
	}
	public static String toHexString(byte[] bytes){
		int len=bytes.length;
		String[] strs=new String[len];
		for(int i=0;i<len;i++){
			String v=Integer.toHexString(Byte.toUnsignedInt(bytes[i])).toUpperCase();
			if(v.length()<2){
				strs[i]="0"+v;
			}else{
				strs[i]=v;
			}
		}
		return StringUtils.arrayToDelimitedString(strs, " ");
	}
	public static byte[] fromHexString(String str){
		String[] vals=str.split("\\s+");
		int len=vals.length;
		byte[] rs=new byte[len];
		for(int i=0;i<len;i++){
			rs[i]=Integer.valueOf(vals[i], 16).byteValue();
		}
		return rs;
	}
	public static byte[] toByteArray(int ... vals){
		int len=vals.length;
		byte[] rs=new byte[len];
		
		return rs;
	}
	public static int newByte(String val){
		int radix=10;
		String s=null;
		val=val.toLowerCase();
		if(val.startsWith("0x")){
			radix=16;
			s=val.substring(2);
		}else if(val.startsWith("0")){
			radix=8;
			s=val.substring(1);
		}else{
			s=val;
		}
		return Integer.valueOf(s, radix);
	}
	public static void main(String[] args) {
		System.out.println(toHexString(fromHexString("")));
	}
}
